/**
 * Created by Oswald on 2017/2/8.
 */
$(document).ready(function(){

    GetBatchOrderList();
    InitAboutNeeded();
    SetPanelGourpDivTop();
    InitBtnStatus();


    //选中表的行事件
    $('#tableBatchOrder').on('check.bs.table', function (e, row){
        //拿到行选中的数据
        var orderId = row["id"];

        //显示工艺配方信息
        GetCraftRecipe(orderId);

        var status = row['statusName'];
        //改变按钮状态
       ChangeBtnStatus(status);

        //改变面板状态和数据
        ChangePanelStatus(status,orderId);
    });

    /*******************************************************按钮事件部分*************************************************/
    //刷新
    $('#btnRefreshBatch').click(function(){
        InitBtnStatus();
        GetBatchOrderList();
    });

    //新增
    $('#btnAddBatch').click(function(){
        var html = 'AddBatchOrder.html';
        TuLayer.ShowDiv(html,'新增批指令','420px','600px',function(){
        })
    })

    //拷贝
    $('#btnCopyBatch').click(function(){
        var html = 'CopyBatchOrder.html';
        TuLayer.ShowDiv(html,'拷贝批指令','420px','400px',function(){

        })
    })

    //生效
    $('#btnEffectBatch').click(function(){
        var html = 'BatchOrderEffect.html';
        TuLayer.ShowDiv(html,'生效批指令','900px','600px',function(){
            //显示批指令基本信息
            EffectPageShowOrderBasic();

            //显示操作指令表
            EffectPageShowOperateOrderList();

            //生效画面显示BOM列表
            EffectPageShowBOMInfo();

            //确认按钮
            $('#batchEffectEnsure').click(function(){
                var v = ValidateWorkCenterSelected();
                if(v){
                    EffectBatachOrderConfirm();
                }
            })
        })
    })

    //编辑
    $('#btnEditBatch').click(function(){
        var html = 'BatchOrderUpdate.html';
        TuLayer.ShowDiv(html,'编辑批指令','420px','350px',function(){
            //显示批指令基本信息
            UpdatePageShowOrderBasic();

            //升级确认按钮
            $('#Update_BatchOrder_Confirm').click(function(){
                UpdatePageComfirm();
            })
        })
    })

    //重置
    $('#btnResetBatch').click(function(){
        var orderId =  $('#tableBatchOrder').bootstrapTable('getSelections')[0].id;
        var url = serverPath + 'Order/resetOrder';
        ibcpLayer.ShowConfirm('您确定要重置选择的批指令吗？', function(){
            Signature.CallSign(100,function(sid){
                var datas = {'id':orderId,'sid':sid};
                ibcpAjax.Update(url,datas,true,function(){
                    Signature.CloseSign();
                    ibcpLayer.ShowOK('重置成功');
                    GetBatchOrderList();
                });
            })
        });
    })

    //终止
    $('#btnStopBatch').click(function(){
        var orderId =  $('#tableBatchOrder').bootstrapTable('getSelections')[0].id;
        var url = serverPath + 'Order/terminateOrder';
        ibcpLayer.ShowConfirm('您确定要终止选择的批指令吗？', function(){
            Signature.CallSign(100,function(sid){
                var datas = {'id':orderId,'sid':sid};
                ibcpAjax.Update(url,datas,true,function(){
                    Signature.CloseSign();
                    ibcpLayer.ShowOK('终止成功');
                    GetBatchOrderList();
                });
            })
        });
    })

    //删除
    $('#btnDeleteBatch').click(function(){
        var orderId =  $('#tableBatchOrder').bootstrapTable('getSelections')[0].id;
        var url = serverPath + 'Order/deleteOrder';
        ibcpLayer.ShowConfirm('您确定要删除选择的批指令吗？', function(){
            Signature.CallSign(100,function(sid){
                var datas = {'id':orderId,'sid':sid};
                ibcpAjax.Delete(url,datas,true,function(){
                    Signature.CloseSign();
                    ibcpLayer.ShowOK('删除成功');
                    GetBatchOrderList();
                });
            })
        });
    })

    //隐藏或者展开列表
    $('#hideAndShow').click(function(){
        var status = $('#hideAndShow').attr('status');

        //如果是展开状态，就隐藏
        if(status == 'show'){
           //显示只有选中行的表格
            $('#orderDiv').hide();
            //获取选中的行，插入浮动的表(先删除原来的，再插入)
            var selectRow = $('#tableBatchOrder').bootstrapTable('getSelections');
            $('#tableBatchOrderFloat').bootstrapTable("prepend", selectRow);
            $('#tableBatchOrderFloat').bootstrapTable("checkAll");
            $('#tableBatchOrderFloat').tableHideCheckbox();
            $('#floatDiv').show();

            //设置按钮status属性
            $('#hideAndShow').attr('status','hide');
        }

        //如果是隐藏状态就展开
        if(status == 'hide'){
            //显示包含所有数据的表格
            $('#floatDiv').hide();
            $('#tableBatchOrderFloat').bootstrapTable("removeAll");
            $('#orderDiv').show();

            //设置按钮status属性
            $('#hideAndShow').attr('status','show');
        }

        SetPanelGourpDivTop();

    });

    /*******************************************************收缩面板部分*************************************************/
        //显示工艺配方信息
    $('#craftRecipePanel').on('show.bs.collapse', function () {
        var orderId = $('#tableBatchOrder').bootstrapTable('getSelections')[0].id;
        GetCraftRecipe(orderId);
    })

    //显示操作指令
    $('#operateOrderPanel').on('show.bs.collapse',function(){
        var orderId = $('#tableBatchOrder').bootstrapTable('getSelections')[0].id;
        GetOperateOrder(orderId);
    })

    //显示BOM信息
    $('#bomPanel').on('show.bs.collapse',function (){
        var orderId = $('#tableBatchOrder').bootstrapTable('getSelections')[0].id;
        GetBOMInfo(orderId);
    })

    //显示偏差信息
    $('#deviationPanel').on('show.bs.collapse',function (){

    })

    //显示甘特图
    $('#ganttChartPanel').on('show.bs.collapse',function (){

    })

    //显示批记录
    $('#batchRecordPanel').on('show.bs.collapse',function (){

    })

});

//-------------------------------------------批指令查看画面-----------------------------------------------
//获取工艺配方信息
function GetCraftRecipe(orderId){
    var param = {'id':orderId};
    var url = serverPath +  'recipe/findRecipeDetailByOrderId';
    ibcpAjax.Select(url,param,true,function(result){
        var data = [];
        data.push(result.data);
        $('#craftRecipeTable').bootstrapTable('load',data);
    })
}

//获取操作指令信息
function GetOperateOrder(orderId){
    var param = {'orderId':orderId};
    var url = serverPath + 'workCenterOrder/findWorkCenterOrderByOrderId';
    ibcpAjax.Select(url,param,true,function(result){
        var data = result.data;
        $('#operateOrderTable').bootstrapTable('load',data);
    })
}

//获取BOM信息
function GetBOMInfo(orderId){
    var param = {'orderId':orderId};
    var url = serverPath + 'Order/findOrderBom';
    ibcpAjax.Select(url,param,true,function(result){
        var data = result.data;
        $('#bomTable').bootstrapTable('load',data);
    })
}

//初始化按钮状态
function InitBtnStatus(){
    $('#btnDeleteBatch').attr('disabled',true);
    $('#btnStopBatch').attr('disabled',true);
    $('#btnResetBatch').attr('disabled',true);
    $('#btnEditBatch').attr('disabled',true);
    $('#btnEffectBatch').attr('disabled',true);
    $('#btnCopyBatch').attr('disabled',true);
}

//修改按钮可用状态
function ChangeBtnStatus(status){
    //编辑、删除仅在计划状态可用
    if(status == "计划"){
        $('#btnEffectBatch').attr('disabled',false);
        $('#btnEditBatch').attr('disabled',false);
        $('#btnDeleteBatch').attr('disabled',false);
    }else {
        $('#btnEffectBatch').attr('disabled',true);
        $('#btnEditBatch').attr('disabled',true);
        $('#btnDeleteBatch').attr('disabled',true);
    }
    //重置仅在生效状态可用
    if(status == '生效'){
        $('#btnResetBatch').attr('disabled',false);
    }else {
        $('#btnResetBatch').attr('disabled',true);
    }
    //终止仅在生产中状态可用
    if(status == '生产中'){
        $('#btnStopBatch').attr('disabled',false);
    }else {
        $('#btnStopBatch').attr('disabled',true);
    }
    $('#btnCopyBatch').attr('disabled',false);
}

//改变面板的状态
function ChangePanelStatus(status,orderId){
    if(status == '计划'){
        $('#bOperateOrderPanel').hide();
        $('#bBomPanel').hide();
        $('#bDeviationPanel').hide();
        $('#bGanttChartPanel').hide();
        $('#bBatchRecordPanel').hide();
    }else {
        $('#bOperateOrderPanel').show();
        $('#bBomPanel').show();
        $('#bDeviationPanel').show();
        $('#bGanttChartPanel').show();
        $('#bBatchRecordPanel').show();

        if($('#operateOrderPanel').is('.in')){
            GetOperateOrder(orderId);
        }
        if($('#bomPanel').is('.in')){
            GetBOMInfo(orderId);
        }
    }
}

//获取批指令数据
function GetBatchOrderList(){
    var param = {'limitNo':5};
    var url = serverPath + "Order/queryOrderList";
    ibcpAjax.Select(url,param,true,function(result){
        var data = result.data;
        $('#tableBatchOrder').bootstrapTable('load',data);
        //隐藏checkBox
        $("#tableBatchOrder").tableHideCheckbox();
        //选中第一行
        if(data.length > 0){
            $('#tableBatchOrder').bootstrapTable('check','0');
        }
    });
}

//设置折叠可以多个显示
function InitAboutNeeded(){
    //设置折叠可以多个显示
    $(".panel-collapse").collapse({
        toggle: false
    });

    //面板收缩指向图标
    $('.panel-heading').click(function(){
        var sp = $(this).find('.panel-title span,.glyphicon-triangle-bottom');
        sp.toggleClass("glyphicon-triangle-top");
    })
}

//动态设置浮动表格的宽,panelbody的Top
function SetPanelGourpDivTop(){
    var status = $('#hideAndShow').attr('status');
    //判断当前顶部显示的是哪个表格
    var topDiv = $('#orderDiv');
    if(status == 'hide'){
        topDiv = $('#floatDiv');
    }

    var topDivTop = topDiv.offset().top;
    var topDivH = topDiv.outerHeight();

    var panelGroupTop = topDivTop + topDivH + 10;
    $('#panelGroup').css('top',panelGroupTop);
}

//窗体大小变化事件
$(window).resize(function(){
    SetPanelGourpDivTop();
    $('#tableBatchOrder').bootstrapTable('resetView');
    $('#tableBatchOrderFloat').bootstrapTable('resetView');
});

//-------------------------------------------生效批指令-----------------------------------------------
//生效画面显示批指令基本信息
function EffectPageShowOrderBasic(){
    var seleted = $('#tableBatchOrder').bootstrapTable('getSelections')[0];
    var orderNo = seleted.orderNo;
    var materialCode = seleted.materialCode;
    var materialCodeName =  seleted.materialCodeName;
    var spec = seleted.spec;
    var batchNo =  seleted.batchNo;
    var planQuantity =  seleted.planQuantity;
    var uomSymbol = seleted.uomSymbol;

    $('#inOrderNo').val(orderNo);
    $('#inMatCode').val(materialCode);
    $('#inMatName').val(materialCodeName);
    $('#inSpec').val(spec);
    $('#inBatchNo').val(batchNo);
    $('#inQuantity').val(planQuantity + '(' + uomSymbol + ')');

}

//生效画面显示操作指令表
function EffectPageShowOperateOrderList(){
    var orderId =  $('#tableBatchOrder').bootstrapTable('getSelections')[0].id;
    var param = {'id':orderId};
    var url = serverPath +  'Order/buildPreviewOrder';
    ibcpAjax.Select(url,param,true,function(result){
        var data = result.data;
        $('#eOperateOrderTable').bootstrapTable();
        $('#eOperateOrderTable').bootstrapTable('load',data);
    })
}

//生效画面显示BOM列表
function EffectPageShowBOMInfo(){
    var orderId =  $('#tableBatchOrder').bootstrapTable('getSelections')[0].id;
    var param = {'id':orderId};
    var url = serverPath +  'Order/computeOrderBom';
    ibcpAjax.Select(url,param,true,function(result){
        var data = result.data;
        $('#bomInforTable').bootstrapTable();
        $('#bomInforTable').bootstrapTable('load',data);
    })
}

//初始化工位组选择工位按钮
function operateFormatter(value, row, index) {
    var type = row.copyWorkType;
    var strColor = 'red';
    var id = row.copyWorkId;
    if(row.targetWorkType == '1'){
        strColor = 'green';
    }

    if(type == '2'){
        return [
            '<div class="pull-left">',
            '<span style="color: '+ strColor +'">' + value + '</span>',
            '</div>',
            '<div class="pull-right">',
            '<a workId=' + id + ' class="selectWorkNameIcon" href="javascript:void(0)">',
            '<i class="glyphicon glyphicon-edit"></i>',
            '</a>  ',
            '</div>'
        ].join('');
    }
    else {
        return value;
    }
}

//选择工位按钮事件
window.selectWorkName = {
    'click .selectWorkNameIcon': function (e, value, row,index) {
        var groupId = $(this).attr("workId");

        var html = '../WorkCenter/WorkCenterSelect.html';
        TuLayer.ShowDiv(html,'选择工位','400px','310px',function(){
            //加载工位列表
            $('#WorkCenterList').bootstrapTable();
            LoadWorkCenter(groupId);

            $('#btnWorkCenterChose').on('click', function (){
                WorkCenterChose(index);
                TuLayer.Close();
            });

        })
    }
};

//工位选择验证
function ValidateWorkCenterSelected(){
    var data = $('#eOperateOrderTable').bootstrapTable('getData');
    for(var i=0; i<data.length; i++){
        var row = data[i];
        if(row.targetWorkType == '2'){
            ibcpLayer.ShowMsg('工位组:' + row.targetWorkName + ' 未选择工位');
            return false;
        }
    }
    return true;
}

//加载 WorkCenter 数据
function LoadWorkCenter(groupId){
    var param = {'id':groupId};
    var url = serverPath +  'WorkCenterGroups/getMembers';
    ibcpAjax.Select(url,param,true,function(result){
        var data = result.data;
        $('#WorkCenterList').bootstrapTable('load',data);
        if(data.length >0) {
            //设置选中行
            $('#WorkCenterList').bootstrapTable('check', 0);
        }
    })
}

//选中工位确认
function WorkCenterChose(index){
    var wcSelect = $('#WorkCenterList').bootstrapTable('getSelections')[0];
    $('#eOperateOrderTable').bootstrapTable('updateRow',{
        index: index,
        row: {
            targetWorkId: wcSelect.id,
            targetWorkCode: wcSelect.code,
            targetWorkName: wcSelect.name,
            targetWorkType: '1'
        }
    });
}

//生效批指令
function EffectBatachOrderConfirm(){
    var orderId =  $('#tableBatchOrder').bootstrapTable('getSelections')[0].id;
    var recipePathResource = JSON.stringify($('#eOperateOrderTable').bootstrapTable('getData'));
    var orderBoms = JSON.stringify($('#bomInforTable').bootstrapTable('getData'));

    Signature.CallSign(100,function(sid){
        var datas = {'id':orderId,'sid':sid,'RecipePathResource':recipePathResource,'orderBoms':orderBoms};
        var url = serverPath + 'Order/effectOrder';
        ibcpAjax.Insert(url,datas,true,function(){
            Signature.CloseSign();
            TuLayer.Close();
            GetBatchOrderList();
        });
    })
}

//-------------------------------------------编辑批指令-----------------------------------------------
//画面显示
function UpdatePageShowOrderBasic(){
    var selected = $('#tableBatchOrder').bootstrapTable('getSelections')[0];
    var orderNo = selected.orderNo;
    var batchNo = selected.batchNo;
    var matName = selected.materialCodeName;
    var quantity = selected.planQuantity;
    var uom = selected.uomSymbol;
    var planDate = selected.planDate;
    //删除日期的时分秒
    var dateArr = planDate.split(' ');
    var data = dateArr[0];

    $('#Order_Update_No').val(orderNo);
    $('#Batch_Update_No').val(batchNo);
    $('#Update_Product_Name').val(matName);
    $('#Batch_Update_Quantity').val(quantity);
    $('#Update_Product_Unit').text(uom);
    $('#BatchOrder_Update_PlanDate').val(data);
}

//升级方法事件
function UpdatePageComfirm(){
    var batchNo = $('#Batch_Update_No').val();
    var planQuantity = $('#Batch_Update_Quantity').val();
    var planDate = $('#BatchOrder_Update_PlanDate').val();

    if($('#Batch_Update_No').val() == ''){
        ibcpLayer.ShowTips('请输入批号',$('#Batch_Update_No'));
        return;
    }
    if($('#Batch_Update_Quantity').val() == ''){
        ibcpLayer.ShowTips('请输入批量',$('#Batch_Update_Quantity'));
        return;
    }
    if($('#BatchOrder_Update_PlanDate').val() == ''){
        ibcpLayer.ShowTips('请输入日期',$('#BatchOrder_Update_PlanDate'));
        return;
    }

    //拼接时间
    var time = " 00:00:00";
    planDate = planDate + time;

    var orderId =  $('#tableBatchOrder').bootstrapTable('getSelections')[0].id;

    Signature.CallSign(100,function(sid){
        var datas = {'id':orderId,'sid':sid,'batchNo':batchNo,'planQuantity':planQuantity,'planDate':planDate};
        var url = serverPath + 'Order/updateOrder';
        ibcpAjax.Update(url,datas,true,function(){
            Signature.CloseSign();
            TuLayer.Close();
            GetBatchOrderList();
        });
    })
}
